
uniform sampler2D baseMap;
uniform int nbLights;
float shininess = 256.0;

varying vec3 normal;		// vertex normal
varying vec3 posEye;		// vertex in eye space

void main(void)
{
	// texture color
	vec3 baseColor = texture2D(baseMap, gl_TexCoord[0].st).rgb;
	float alpha = texture2D(baseMap, gl_TexCoord[0].st).a;

	vec3 resColor = vec3(0,0,0);
		
	for(int i = 0; i < nbLights; i++)
	{
		// compute ambient	
		vec3 ambient = gl_FrontMaterial.ambient.xyz * gl_LightSource[i].ambient.xyz;

		// compute cos between light dir and normal
		vec3 lightPos = vec3(gl_LightSource[i].position.xyz - posEye);
		vec3 lightDir = normalize(lightPos);
		
		float NdotL = dot(normal, lightDir);
		
		float selfShadow = (NdotL > 0.0) ? 1.0 : 0.0;

		// compute diffuse
		vec3 diffuse = gl_FrontMaterial.diffuse.xyz * gl_LightSource[i].diffuse.xyz * NdotL;

		// compute specular with half vector
		vec3 specular = vec3(0);
		if(shininess >= 0.0)
		{
			float NdotHV = max(dot(normal, gl_LightSource[i].halfVector.xyz), 0.0);
			specular = selfShadow * gl_LightSource[i].specular.xyz * pow(NdotHV, shininess);
		}
		
		// mix base color with ambient, diffuse and specular terms
		resColor += baseColor * (ambient + diffuse) + specular;
	}
	resColor /= (float)nbLights;
	
	gl_FragColor = vec4(resColor, alpha);
}
